package org.alex.farouq.exam.view;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import org.alex.farouq.exam.controller.Controller;

import sun.tools.tree.Node;

public class MainWindow extends javax.swing.JFrame {
	QuestionWindow questionWindow;
	public Controller control;

	public enum ButtonClicked {
		addQuestionButtonClicked, previewQuestionButtonClicked, removeQuestionButtonClicked, removeSubQuestionButtonClicked;
	}

	/** Creates new form NewJFrame2 */
	public MainWindow() {
		setResizable(false);
		questionWindow = new QuestionWindow();
		setTitle("Exam Generator");
		control = Controller.getInstance();
		control.addObserver(this);
		initComponents();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jDesktopPane1 = new javax.swing.JDesktopPane();
		jTextField1 = new javax.swing.JTextField();
		totalExamMarksLabel = new javax.swing.JLabel();
		removeSelectedQuestionButton = new javax.swing.JButton();
		addNewQuestionButton = new javax.swing.JButton();
		combinationNumberLabel = new javax.swing.JLabel();
		removeSelectedSubQuestionButton = new javax.swing.JButton();
		generateExamButton = new javax.swing.JButton();
		previewSelectedQuestionButton = new javax.swing.JButton();
		totalExamDurationLabel = new javax.swing.JLabel();
		jScrollPane1 = new javax.swing.JScrollPane();

		root = new DefaultMutableTreeNode("Exam");

		jTree = new javax.swing.JTree(root);
		jTree.getSelectionModel().setSelectionMode(
				TreeSelectionModel.SINGLE_TREE_SELECTION);

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jDesktopPane1.setBackground(new java.awt.Color(255, 255, 255));

		jTextField1.setBounds(200, 310, 190, 20);
		jDesktopPane1.add(jTextField1, javax.swing.JLayeredPane.DEFAULT_LAYER);

		totalExamMarksLabel.setBounds(15, 350, 210, 20);
		jDesktopPane1.add(totalExamMarksLabel,
				javax.swing.JLayeredPane.DEFAULT_LAYER);

		removeSelectedQuestionButton.setText("Remove Selected Question");
		// to differentiate between event sources in listener method
		removeSelectedQuestionButton.setName("3");
		removeSelectedQuestionButton.addActionListener(control);
		removeSelectedQuestionButton.setBounds(190, 140, 210, 23);
		jDesktopPane1.add(removeSelectedQuestionButton,
				javax.swing.JLayeredPane.DEFAULT_LAYER);

		addNewQuestionButton.setText("Add New Question");
		// to differentiate between event sources in listener method
		addNewQuestionButton.setName("1");

		addNewQuestionButton.addActionListener(control);

		addNewQuestionButton.setBounds(220, 60, 140, 23);
		jDesktopPane1.add(addNewQuestionButton,
				javax.swing.JLayeredPane.DEFAULT_LAYER);

		combinationNumberLabel.setBounds(210, 260, 160, 30);
		jDesktopPane1.add(combinationNumberLabel,
				javax.swing.JLayeredPane.DEFAULT_LAYER);

		removeSelectedSubQuestionButton.setText("Remove Selected SubQuestion");
		// to differentiate between event sources in listener method
		removeSelectedSubQuestionButton.setName("4");
		removeSelectedSubQuestionButton.addActionListener(control);
		removeSelectedSubQuestionButton.setBounds(190, 180, 210, 23);
		jDesktopPane1.add(removeSelectedSubQuestionButton,
				javax.swing.JLayeredPane.DEFAULT_LAYER);

		generateExamButton.setText("Generate Exam");
		generateExamButton.setName("5");
		generateExamButton.addActionListener(control);
		generateExamButton.setBounds(230, 350, 130, 40);
		jDesktopPane1.add(generateExamButton,
				javax.swing.JLayeredPane.DEFAULT_LAYER);

		previewSelectedQuestionButton.setText("Preview Selected Question");
		// to differentiate between event sources in listener method
		previewSelectedQuestionButton.setName("2");
		previewSelectedQuestionButton.addActionListener(control);
		previewSelectedQuestionButton.setBounds(190, 100, 210, 23);
		jDesktopPane1.add(previewSelectedQuestionButton,
				javax.swing.JLayeredPane.DEFAULT_LAYER);

		totalExamDurationLabel.setBounds(15, 390, 210, 14);
		jDesktopPane1.add(totalExamDurationLabel,
				javax.swing.JLayeredPane.DEFAULT_LAYER);

		jScrollPane1.setViewportView(jTree);

		jScrollPane1.setBounds(10, 10, 160, 300);
		jDesktopPane1.add(jScrollPane1, javax.swing.JLayeredPane.DEFAULT_LAYER);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addComponent(
				jDesktopPane1, javax.swing.GroupLayout.Alignment.TRAILING,
				javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE));
		layout.setVerticalGroup(layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addComponent(
				jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 454,
				Short.MAX_VALUE));

		pack();
	}// </editor-fold>

	// this button write in it method of controller that handel add question
	public void addNewQuestionButtonActionPerformed() {
		questionWindow.setVisible(true);
	}

	public void addNewQuestion(String questionName) {
		DefaultMutableTreeNode newQuestionNode = new DefaultMutableTreeNode(
				questionName);

		root.add(newQuestionNode);
	
		// TODO add subquestions nodes
		jTree.updateUI();
	}

	private void setEditing(boolean b, int index) {
		isEditing = b;
		currenSelectedIndex = index;
	}

	public void addEditQuestionItemActionPerformed(String itemName) {
		if (isEditing) {
			// TODO change node name
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree
					.getLastSelectedPathComponent();
			int index = root.getIndex(node);
			
			root.remove(index);
			
			DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(
					itemName);
			
			root.insert(newNode, index);
			 
			isEditing = false;
			jTree.updateUI();
		} else {
			this.addNewQuestion(itemName);
		}

	}

	public int previewSelectedQuestionButtonActionPerformed() {
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree
				.getLastSelectedPathComponent();
		int index;
		if (node == null || node.getParent() != root || node == root) {
			index = -1;
		} else {
			index = root.getIndex(node);
		}
		if (index != -1) {
			setEditing(true, index);
		} else {
			JOptionPane
					.showMessageDialog(this, "please select an item to edit");
		}
		return index;
	}

	public void setQuestionToBeEdited(String header, int typeIndex,
			String[] subQuestions) {

		questionWindow.showEditedQuestion(header, typeIndex, subQuestions);
		questionWindow.setVisible(true);

	}

	

	public void setCombinationNumber(int combinationNumber) {
		combinationNumberLabel.setText("      " + combinationNumber + " ");
	}

	public void upateTotalExamMarkAndDurationLabels(int totalmark, int duration) {
		totalExamMarksLabel.setText("Total Exam Marks = " + totalmark);
		totalExamDurationLabel.setText("Total Exam Duration = " + duration
				+ " mins");
		jDesktopPane1.updateUI();
	}

	public int removeSelectedQuestion() {
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree
				.getLastSelectedPathComponent();
		TreePath t = jTree.getAnchorSelectionPath();
		if (node == null || node.getParent() != root || node == root) {
			return -1;
		}

		int returnValue = root.getIndex(node);
		root.remove(node);
		jTree.removeSelectionPath(t);
		jTree.updateUI();
		return returnValue;
	}

	public int[] removeSelectedSubQuestion() {
		TreePath t = jTree.getAnchorSelectionPath();

		DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree
				.getLastSelectedPathComponent();

		if (node == null || node.getParent() == root || node == root) {
			JOptionPane.showMessageDialog(this,
					"please Select a SubQuestion to remove");
			return null;
		}

		int[] returnValue = new int[2];
		// questionIndex
		returnValue[0] = root.getIndex(node.getParent());
		// subQuestionIndex
		returnValue[1] = node.getParent().getIndex(node);

		((DefaultMutableTreeNode) node.getParent()).remove(node);
		jTree.removeSelectionPath(t);
		jTree.updateUI();
		return returnValue;
	}

	
	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
					.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(QuestionWindow.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(QuestionWindow.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(QuestionWindow.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(QuestionWindow.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		}
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new MainWindow().setVisible(true);
			}
		});
	}
	// Variables declaration - do not modify
	private javax.swing.JButton addNewQuestionButton;
	private javax.swing.JButton previewSelectedQuestionButton;
	private javax.swing.JButton removeSelectedQuestionButton;
	private javax.swing.JButton removeSelectedSubQuestionButton;
	private javax.swing.JButton generateExamButton;
	private javax.swing.JDesktopPane jDesktopPane1;
	private javax.swing.JLabel combinationNumberLabel;
	private javax.swing.JLabel totalExamMarksLabel;
	private javax.swing.JLabel totalExamDurationLabel;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JTextField jTextField1;
	private JTree jTree;
	private DefaultMutableTreeNode root;
	boolean isEditing;
	int currenSelectedIndex;
	// End of variables declaration

}
